<template>
<div class="upload-box" id="uploadBox">
      <el-row class="text-left upload-title" v-show="!readonly && !noTitle">
        <el-col :span="24">
          <strong>{{title}}</strong>
          <small style="padding-left: 22px;">(文件数量限制:{{fileMaxNum}})</small>
          <small style="color: #e6a23c;padding-left: 22px;" v-show="noSave">请先保存主单据<i class="el-icon-warning"></i></small>
        </el-col>
      </el-row>
      <el-upload class="upload " ref="elUpload" v-show="showUpload" :class="{'oneline':isOneLine,'oneline-full':isOneLineFull,'is-showdate':isShowDate, 'readonly': readonly}"
                 :action="baseApi+'/tool/uploadMore'"
                 multiple
                 :limit="fileMaxNum"
                 :on-exceed="handleExceed"
                 :on-success="handleSuccess"
                 :before-upload="handleBeforeUpload"
                 :data="uploadParam"
                 :headers="headers"
                 :file-list="fileList" list-type="picture-card"
      >
        <!--v-show="fileList.length < fileMaxNum"-->
        <i slot="default" class="el-icon-plus" ></i>
        <div slot="file" slot-scope="{file}" :title="file.name" >
          <div class="img-title">{{file.name}}
          </div>
          <div class="img-title"  v-show="isShowDate" style="text-align: right;padding-right: 11px">
            <small style="padding-right: 11px">操作人：{{file.creator}}</small>
            <small>操作时间：{{file.gmtCreate}}</small>
          </div>
          <img :onerror="'1111111111111'"
            class="el-upload-list__item-thumbnail"
            :src="file.url" alt=""  v-show = 'propIsView || isImg(file)'
          >
          <span class="el-upload-list__item-actions">
        <span
          class="el-upload-list__item-preview"
          @click="handlePictureCardPreview(file)"
          v-show="isImg(file) || isPdfView(file.name) || propIsView"
          :title="`预览${file.name}`"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
          v-if="!disabled"
          class="el-upload-list__item-delete"
          @click="handleDownload(file)"
          :title="`下载${file.name}`"
        >
          <i class="el-icon-download"></i>
        </span>
        <span
          v-if="!disabled"
          v-show="!readonly"
          class="el-upload-list__item-delete"
          @click="handleRemove(file)"
          :title="`删除${file.name}`"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
        </div>
      </el-upload>
      <el-row style="width: 0px;height: 0px;">
        <el-col :span="24">
          <el-image ref="elImage" style="width: 0px;height: 0px;"
                    :src="previewSrc"
                    :error="previewErr"
                    :preview-src-list="previewSrcList">
          </el-image>
        </el-col>
      </el-row>
</div>


</template>

<script>
/* eslint-disable*/
export default {
  name: 'Upload',
  data() {
    return {
      activeNames: ['1'],
      dialogImageUrl: '',
      dialogVisible: false,
      noSave: true,
      showUpload: false,
      uploadParam: {},
      disabled: false,
      enabledOpArea: true,
      showUploadNoAdd: true,
      fileList: [],
      previewSrcList: [],
      previewSrc: '',
      headers: {},
      fileTypeImg: 'jpeg,jpg,png,icon',
      fileTypeImport: 'xls',
      fileTypeAll: 'doc,docx,xls,xlsx,txt,pdf,jpeg,jpg,png,icon',
      fileTypes: 'doc,docx,xls,xlsx,txt,pdf,jpeg,jpg,png,icon',
      baseApi: location.origin+'/api'
    };
  },
  props: {
    fileType: {String,default:'all'},//文件类型,可选 img:图片类，all: fileTypeAll文件,import
    fileSize: {Number,default:1},//文件大小限制，单位为MB
    fileMaxNum: {Number,default:1},//文件上传最大数量
    title: {String,default:'文件上传'},//文件区域文字
    fileSavePath: {type: String, default: 'tmp'},//文件保存路径,从res:real-path 开始
    fileRefTable: {String,default:null},//文件关联表
    propStatus: {String},//文件关联id
    fileRefId: {String,default:null},
    readonly: {Boolean,default:false},//是否只读，true:隐藏删除、上传区域
    noTitle: {Boolean,default:false},//是否不显示标题，true:隐藏标题
    isOneLine: {Boolean,default:false},//单行样式
    isOneLineFull: {Boolean,default:false},//预览区域独占一行
    isShowDate: {Boolean,default:false},//是否显示上传时间
    propIsView: {Boolean,default:false},//强制进行预览
    autoLoadFile: {Boolean,default:true},//false: 初始化或者删除之后不加载数据
    showLastFile: {Boolean,default:false},//true: 只显示最后一次上传的文件
    isReverseData: {Boolean,default:false},//true:反转数组，即按时间降序
    propFileList: {Array,default:null},//有的话则，追加到显示列表,[{name:'',url}]
  },
  methods: {
    isPdfView(fileName) {
      let typeName=fileName.substring(fileName.lastIndexOf('.')+1);
      return  typeName.toLowerCase() == 'pdf' || typeName.toLowerCase() == 'docx'
    },
    //判断是否是图片
    isImg(file) {
      if(!file || !file.fileName ) return false
      let typeName=file.fileName.substring(file.fileName.lastIndexOf('.')+1);
      return this.fileTypeImg.indexOf(typeName) != -1
    },
    opAreaShowHide(fileListNew) {
      if(fileListNew.length >= this.fileMaxNum || this.readonly){
        $(this.$refs.elUpload.$el).find('.el-upload--picture-card').hide()
      }else{
        $(this.$refs.elUpload.$el).find('.el-upload--picture-card').show()
      }
    },
    //上传前校验
    handleBeforeUpload(file) {
      let typeName=file.name.substring(file.name.lastIndexOf('.')+1);
      if(this.fileTypes.indexOf(typeName) == -1){
        this.utilMessage.error('文件类型限制为:'+this.fileTypes)
        return  false;
      }
      if(file.size > (this.fileSize*1024*1024)){
        this.utilMessage.error(`文件最大为${this.fileSize}MB，当前文件大小:${(file.size/1024/1024).toFixed(2)}MB`)
        return  false;
      }

      return true
    },
    //删除后
    async handleRemove(file, fileList) {

      const result = await this.$confirm('是否删除该文件?')
      if (!result)  return ;
      this.utilVue.loadShow(true,'#elUpload')
      await this.$ajax.get(`${this.baseApi}/tool/delFilesByRef?fileId=${file.id}`, {}).then((response) => {
        let data=response.data;
        if (response.code == 0) {
          this.utilMessage.success(response.msg)
          this.$emit('remove-success', file)
          if (!this.autoLoadFile) {
            this.fileList = []
            this.previewSrcList = []
            this.opAreaShowHide(this.fileList)
            return
          } else {
            this.loadFiles()
          }
        }
        this.utilVue.loadHide()
      }).finally(() => {
        this.utilVue.loadHide()
      }).catch(() => {
        this.utilVue.loadHide()
      })

    },
    //预览
    handlePictureCardPreview(file) {
      if (this.propIsView) {
        this.utilPrint.openPdf(file.filePath)
        return
      }

      let typeName=file.fileName.substring(file.fileName.lastIndexOf('.')+1);
      if (this.isPdfView(typeName)) {
        this.utilPrint.openPdf(file.filePath)
        return
      }
      this.previewSrc = file.url;
      this.$refs.elImage.showViewer = true
    },
    handleExceed(files, fileList) {
      this.utilMessage.warning(`上传文件数量最大上限为${this.fileMaxNum}`);
    },
    //上传操作
    handleSuccess(response, file, fileList) {
      let type = 'success'
      if(response.code != 0){
        type = 'error'
        let delIndex=this.fileList.findIndex(item => item.url === file.response.data.url)
        this.fileList.splice(delIndex, 1)
        this.opAreaShowHide(fileList)
      }else{
        this.loadFiles()
      }
      if (type == 'success') {
        this.utilMessage.success(response.msg)
        this.$emit('upload-success', file)
      } else {
        this.utilMessage.error(response.msg)
        this.$emit('upload-error', file)
      }

    },
    handleDownload(file) {
      window.open(file.url, "_blank");
    },
    //加载文件
    loadFiles() {
      this.utilVue.loadShow(true,'#elUpload')
      this.fileList=[]
      if (this.propFileList) this.fileList = this.propFileList
      this.$ajax.get(`${this.baseApi}/tool/getFilesByRef?fileRefTable=${this.fileRefTable}&fileRefId=${this.fileRefId}`, {}).then((response) => {
        let data=response.data;
        if (response.code == 0) {
          if(data && data.length >0){
            if (this.showLastFile) data = [data[data.length-1]]
            if (this.isReverseData) data = data.reverse()
            data.forEach(ob => {
              let obIndex=this.fileList.findIndex(item => item.id === ob.id)
              if(obIndex != -1) return true
              ob.name = ob.fileName;
              ob.url = this.baseApi + ob.filePath;
              this.fileList.push(ob);
              this.previewSrcList.push(ob.url)
              this.opAreaShowHide(this.fileList)
            })
          }
        }
        this.utilVue.loadHide()
      }).finally(() => {
        this.utilVue.loadHide()
      }).catch(() => {
        this.utilVue.loadHide()
      })
    },
    //加载文件
    clearFiles() {
      this.fileList = []
      this.previewSrcList = []
      this.opAreaShowHide(this.fileList)
    },
    uploadNoAdd(showUploadParam) {
      this.showUploadNoAdd = showUploadParam
    },
    previewErr(e) {
    }
  },
  created() {
    this.headers['Authorization'] = sessionStorage.getItem('Authorization')
  },
  watch:{
    //视图状态变化后，显示上传操作
    propStatus:{
      handler(newValue, oldValue) {
        if(newValue != 'addnew'){
          this.showUpload=true
          this.noSave = false
        }
      },
      deep: true,
      immediate: true
    },

    //refid 变化后执行
    fileRefId:{
      handler(newValue, oldValue) {
        if(newValue){
          this.showUpload=true
          if(this.fileType == 'img'){
            this.fileTypes = this.fileTypeImg
          } else if(this.fileType == 'import'){
            this.fileTypes = this.fileTypeImport
          }
          this.uploadParam ={
            fileSavePath: this.fileSavePath,
            fileRefTable: this.fileRefTable,
            fileRefId: this.fileRefId
          }
        }
        if (this.autoLoadFile) this.loadFiles()

      },
      deep: true,
      immediate: true
    }

  }
}
</script>

<style scoped lang="scss">
  .upload-box{
    padding: 0px 27px;
    .small{
      line-height:13px !important;
      padding: 0px 0px 7px 9px !important;
    }

    .img-title{
      word-break:keep-all;/* 不换行 */
      white-space:nowrap;/* 不换行 */
      overflow:hidden;/* 内容超出宽度时隐藏超出部分的内容 */
      text-overflow:ellipsis;/* 当对象内文本溢出时显示省略标记(...) ；需与overflow:hidden;一起使用。*/
      padding: 0px 5px;
    }

    .upload-title{
      font-weight: bold;
      font-size: 13px;
      line-height: 32px;
    }
    .upload  /deep/ .el-upload-list__item{
      height: 80px;
      line-height: 80px;
    }
    .upload  /deep/ .el-upload-list__item-thumbnail{
      height: 80px;
      line-height: 80px;
      position: absolute;
      top: 0px;
    }

    .upload  /deep/ .el-upload--picture-card{
      height: 80px;
      line-height: 80px;
    }
    .oneline  /deep/ .el-upload-list__item{
      height: 30px  !important;
      line-height: 30px  !important;
    }

    .oneline-full  /deep/ .el-upload-list__item{
      height: 30px;
      line-height: 30px ;
      width: 100%;
    }

    .is-showdate  /deep/ .el-upload-list__item{
      height: 40px  !important;
    }

    .is-showdate  /deep/ .img-title{
      height: 20px  !important;
      line-height: 20px   !important;
    }

    .oneline  /deep/ .el-upload--picture-card{
      height: 30px !important;
      line-height: 30px  !important;
    }
    .readonly  /deep/ .el-upload--picture-card{
     display: none !important;
    }
  }
</style>
